package leetcode;

import java.util.ArrayList;
import java.util.List;

public class LeetCode129 {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode left = new TreeNode(2);
        TreeNode right = new TreeNode(3);
        root.left = left;
        root.right = right;

        LeetCode129 leetCode129 = new LeetCode129();
        leetCode129.sumNumbers(root);
    }

    List<String> list = new ArrayList<>();

    public int sumNumbers(TreeNode root) {
        if (root == null)
            return 0;
        int result = 0;
        walk(root, "");
        for (String str : list) {
            result += Integer.parseInt(str);
        }
        return result;
    }

    //string 效率太低
    private void walk(TreeNode node, String lastResult) {
        String s = lastResult + node.val;
        if (node.left == null && node.right == null) {
            list.add(s);
            return;
        }
        if (node.left != null)
            walk(node.left, s);
        if (node.right != null)
            walk(node.right, s);
    }

    //关机是定义递归的返回值意义
    //返回每个节点的和
    public int helper(TreeNode root, int i) {
        if (root == null) return 0;
        int temp = i * 10 + root.val;
        if (root.left == null && root.right == null)
            return temp;
        return helper(root.left, temp) + helper(root.right, temp);
    }
//------------------------------------------------------------------
}
